package com.dz.lm.domain;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.lang3.StringUtils;

public class DES {
    private static byte[]      iv  = { 1, 2, 3, 4, 5, 6, 7, 8 };

    public final static String key = "ejavashp";

    public static String encryptDES(String encryptString, String encryptKey) throws Exception {
        //      IvParameterSpec zeroIv = new IvParameterSpec(new byte[8]);
        IvParameterSpec zeroIv = new IvParameterSpec(iv);
        SecretKeySpec key = new SecretKeySpec(encryptKey.getBytes(), "DES");
        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, key, zeroIv);
        byte[] encryptedData = cipher.doFinal(encryptString.getBytes());

        return Base64.encode(encryptedData);
    }

    public static String decryptDES(String decryptString, String decryptKey) throws Exception {
        byte[] byteMi = Base64.decode(decryptString);
        IvParameterSpec zeroIv = new IvParameterSpec(iv);
        //      IvParameterSpec zeroIv = new IvParameterSpec(new byte[8]);
        SecretKeySpec key = new SecretKeySpec(decryptKey.getBytes(), "DES");
        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, key, zeroIv);
        byte decryptedData[] = cipher.doFinal(byteMi);

        return new String(decryptedData, "utf-8");
    }

    public static String encryptDES(String encryptString) {
        try {
            if (StringUtils.isBlank(encryptString)) {
                return encryptString;
            }
            return encryptDES(encryptString, key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return encryptString;
    }

    public static String decryptDES(String decryptString) {
        try {
            if (StringUtils.isBlank(decryptString)) {
                return decryptString;
            }
            return decryptDES(decryptString, key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return decryptString;
    }

    public static void main(String[] args) {
        String text = "北京北京昌平区";
        try {
            String result1 = DES.encryptDES(text, key);
            String result2 = DES.decryptDES("0dOIVfcGBJsNrpzGpfW0wg==", key);
            System.out.println("DES encode text is " + result1);
            System.out.println("DES encode text is " + result2);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
